package com.molihub.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.molihub.entity.HomePage;
import com.molihub.entity.User;
import com.molihub.utils.LogUtils;
import com.molihub.utils.MailUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController extends BaseController {

    private Logger logger = LogUtils.getInstance(UserController.class);

    /**
     * 根据用户名或者用户邮箱查找是否存在该用户
     *
     * @param param 传递过来的用户名或者邮箱
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/1/30
     */
    @ResponseBody
    @GetMapping("/user/find/{param}")
    public String getUserByNameOrEmail(@PathVariable String param) {
        // 1.先进行参数判断，如果包含'@'符号，则表示是邮箱
        String isEmail = "@";
        User user;
        if (param.contains(isEmail)) {
            // 是邮箱
            user = userService.getUserByEmail(param);
        } else {
            // 是用户名
            user = userService.getUserByUserName(param);
        }
        String userJson = JSONObject.toJSONString(user);
        logger.info("用户转json-->:" + userJson);
        return userJson;
    }

    /**
     * 更新用户信息(包括头像，用户名，密码，邮箱)
     *
     * @param user   传递过来的用户信息
     * @return java.lang.String
     * @author PJAVAC
     * @date 2020/2/4
     */
    @RequestMapping(value = "updateUserInfo")
    public String updateUserInfo(User user,String input_province,Map<String, Object> map,String code) {
        if (null!=user.getEmail()&&user.getEmail()!=""){
            if (null!=code&&code!="") {
                String codeKey = user.getEmail()+"_code";
                String realCode = (String) session.getAttribute(codeKey);
                System.out.println(realCode);
                if(!realCode.equals(code)){
                    map.put("info","验证码错误");
                    return "u-admin/update-user-info";
                }
            }
        }else{
            user.setEmail(null);
        }
        if (null!=input_province && input_province!="") {
            user.setLocation(input_province);
        }
        user.setUserId(loginUser.getUserId());
        Integer integer = this.userService.updateUser(user);
        User newUser = userService.getUserById(loginUser.getUserId());
        logger.info("用户" + loginUser.getUserName() + "修改资料成功");
        session.setAttribute("loginUser", newUser);
        return "redirect:/user-info";
    }


    /**
     * @return java.lang.String
     * @Description 修改密码
     * @Author xw
     * @Date 20:44 2020/2/5
     * @Param [oldPwd, newPwd, map]
     **/
    @PostMapping("updatePassword")
    public String updatePassword(String oldPwd, String newPwd, Map<String, Object> map) {
        User user = (User) session.getAttribute("loginUser");
        if (user.getPassword().equals(oldPwd)) {
            Integer integer = userService.updateUser(User.builder().userId(user.getUserId()).password(newPwd).build());
            if (integer == 1) {
                user.setPassword(newPwd);
            }
            return "redirect:/user-info";
        } else {
            map.put("error", "原密码错误，修改失败！");
            return "u-admin/user-info";
        }
    }

    /**
     * 更新用户状态
     *
     * @param flag 状态码
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/7
     */
    @ResponseBody
    @PostMapping("/update/status/{flag}")
    public String updateUserStatus(@PathVariable Integer flag) {
        logger.info("更新后的状态为：" + flag);
        loginUser.setStatus(flag);
        List<User> friends = userFollowService.findAllFriendById(loginUser.getUserId());
        userService.updateUserStatus(loginUser);
        FriendController.notifyFriends(loginUser, friends);
        return "OK";
    }
}
